from selenium import webdriver
import requests
import time
import cv2
import numpy as np
from selenium.webdriver import ActionChains
import redis

def get_pnumber():
    '''从验证码平台获取手机号码'''
    url = "http://api.fxhyd.cn/UserInterface.aspx?action=getmobile&token=014336905694d748cec5aeb75c4cc731e50af0a22601&itemid=995"
    pnumber = requests.get(url).text  # 获得电话号码
    # print(pnumber[8:])
    return pnumber[8:]

def get_code(p):
    '''从验证码平台获取验证码'''
    for i in range(6):
        curl = "http://api.fxhyd.cn/UserInterface.aspx?action=getsms&token=014336905694d748cec5aeb75c4cc731e50af0a22601&itemid=995&mobile={0}&release=1".format(p)
        # print(curl)
        result = requests.get(curl).content.decode('utf-8')  #获取验证码
        # print(result)
        time.sleep(10)
        if len(result)>4:
            return result[17:21]

def get_tracks(space):
    # 模拟人工滑动，避免被识别为机器
    # space += 10  # 先滑过一点，最后再反着滑动回来
    v = 0
    t = 0.2
    forward_tracks = []
    current = 0
    mid = space * 3 / 5
    while current < space:
        if current < mid:
            a = 2
        else:
            a = -3
        s = v * t + 0.5 * a * (t ** 2)
        v = v + a * t
        current += s
        forward_tracks.append(round(s))
    # 反着滑动到准确位置
    back_tracks = [0]
    return {'forward_tracks': forward_tracks, 'back_tracks': back_tracks}

def show(name):
    cv2.imshow('Show', name)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def long():
    otemp = '2.jpg'
    oblk = '1.jpg'
    target = cv2.imread(otemp, 0)
    template = cv2.imread(oblk,0)
    w, h = target.shape[::-1]
    temp = 'temp.jpg'
    targ = 'targ.jpg'
    cv2.imwrite(temp, template)
    cv2.imwrite(targ, target)
    target = cv2.imread(targ)
    target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
    target = abs(-1 - target)
    cv2.imwrite(targ, target)
    target = cv2.imread(targ)
    template = cv2.imread(temp)
    result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)
    x, y = np.unravel_index(result.argmax(), result.shape)
    # long = y+w-30
    # print(x)
    return y
    # # 展示圈出来的区域
    # cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)
    # show(template)

def get_cookies():
    wb = webdriver.Chrome(r'D:\下载安装包文件\chromedriver.exe')
    wb.maximize_window()
    wb.get('https://sso.toutiao.com/')
    wb.implicitly_wait(10)
    while True:
        try:
            phone_number = get_pnumber()  # 从验证码平台获取手机号码
            time.sleep(2)
            wb.find_element_by_xpath('//*[@id="user-mobile"]').send_keys(phone_number)
            time.sleep(1)
            wb.find_element_by_xpath('//*[@id="mobile-code-get"]').click()
            time.sleep(2)
            while True:
                url1 = wb.find_element_by_xpath('//*[@id="validate-big"]').get_attribute('src')  # 图片1
                pdata1 = requests.get(url1).content
                with open('1.jpg', 'rb+') as f:
                    f.write(pdata1)
                    f.close()
                time.sleep(1)
                url2 = wb.find_element_by_xpath('//*[@id="verify-bar-box"]/div[2]/img[2]').get_attribute('src')  # 图片2
                pdata2 = requests.get(url2).content
                with open('2.jpg', 'rb+') as f:
                    f.write(pdata2)
                    f.close()
                time.sleep(1)
                length = long()  # 求出长度
                tracks = get_tracks(length)
                button = wb.find_element_by_xpath('//*[@id="validate-drag-wrapper"]/div[2]/img')
                ActionChains(wb).click_and_hold(button).perform()  # 按住按钮
                for track in tracks['forward_tracks']:  # 前进
                    ActionChains(wb).move_by_offset(xoffset=track, yoffset=0).perform()
                time.sleep(0.5)
                for back_track in tracks['back_tracks']:  # 后退
                    ActionChains(wb).move_by_offset(xoffset=back_track, yoffset=0).perform()
                ActionChains(wb).move_by_offset(xoffset=-3, yoffset=0).perform()
                ActionChains(wb).move_by_offset(xoffset=3, yoffset=0).perform()
                time.sleep(0.5)
                ActionChains(wb).release().perform()  # 释放
                time.sleep(2)
                # 判断结束条件
                if wb.find_element_by_xpath('//*[@id="pc_slide"]').get_attribute(
                        'style') == 'width: 300px; height: 350px; display: none;':
                    break
            code = get_code(phone_number)  # 从验证码平台获取验证码
            wb.find_element_by_xpath('//*[@id="mobile-code"]').send_keys(code)
            wb.find_element_by_xpath('//*[@id="bytedance-login-submit"]').click()
            break
        except:
            wb.refresh()
            time.sleep(2)
    cookies = wb.get_cookies()
    time.sleep(1)
    wb.close()
    return cookies




if __name__== "__main__":
   a=get_cookies()
   print(a)



